<?php
/**
 * Created by Silent Night.
 * Author: Silent Night
 * email: silentwolf_wp@163.com
 * Date: 2017/9/28
 * Time: 9:19
 */

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Session;

class Notes extends Controller
{
    private $_model;
    private $title_field = [
    ];
    public $pagesize = 10;

    public $allTypeLists = array();

    public function _initialize()
    {
        $this->_model = new \app\admin\model\Notes;
        $this->assign('LoginUserInfo', $this->LoginUserInfo);

        //获取当前用户的权限信息
        $this->assign('ruleLists', $this->LoginUserInfo['CurrPower']);

    }

    private function getAllNotesType($ty = 1)
    {
        //获取自然音类型并分配给模板
        $this->allTypeLists = getAllNotesType($ty);
        $this->allTypeLists = changeArrayKey($this->allTypeLists, 'id');
        $this->assign('allTypeLists', $this->allTypeLists);
    }

    public function shangData()
    {
        $return = [];
        $id = trim(input("request.id"));//auth
        if (empty($id)) {
            $return = ['err' => 1, 'msg' => '操作失败'];
            return json($return);
        }
        $res = $this->_model->updateData(array('stats' => 0), $id);
        if ($res || $res === 0) {
            $return = ['err' => 0, 'msg' => '操作成功'];
            return json($return);
        } else {
            $return = ['err' => 3, 'msg' => '操作失败'];
            return json($return);
        }
    }

    public function xiaData()
    {
        $return = [];
        $id = trim(input("request.id"));//auth
        if (empty($id)) {
            $return = ['err' => 1, 'msg' => '操作失败'];
            return json($return);
        }
        $res = $this->_model->updateData(array('stats' => 1), $id);

        if ($res || $res === 0) {
            $return = ['err' => 0, 'msg' => '操作成功'];
            return json($return);
        } else {
            $return = ['err' => 3, 'msg' => '操作失败'];
            return json($return);
        }
    }

    /**
     * 列表页
     * @return mixed
     */
    public function index()
    {
        return $this->fetch('index');
    }


    public function lists()
    {
        $ser_key = trim(input("request.ser_key"));//auth
        $ser_val = trim(input("request.ser_val"));//auth
        $ser_ty = trim(input("request.ser_ty"));//auth
        $ser_pid = trim(input("request.ser_pid"));//auth
        $ser_hot = trim(input("request.ser_hot"));//auth
        $ser_stats = trim(input("request.ser_stats"));//auth

        if ($ser_key && $ser_val) {
            $where[$ser_key] = array('like', '%' . $ser_val . '%');
        }
        if ($ser_ty > 0) {
            $where['ty'] = $ser_ty;
        }
        if ($ser_stats == '0' || $ser_stats == '1') {
            $where['stats'] = $ser_stats;
        }
        if ($ser_hot == '0' || $ser_hot == '1') {
            $where['hot'] = $ser_hot;
        }
        if ($ser_pid) {
            $where['pid'] = $ser_pid;
        }
        $where['is_delete'] = '0';
        $where['ty'] = '1';
        $lists = $this->_model->lists($where, $this->pagesize);
        $lists['data'] = changeUidToUserinfoForLists($lists['data'], 'uid');
        $lists['data'] = filterHtmlForLists($lists['data']);
        $lists['data'] = (new \app\admin\mapper\Common())->listMapper($lists['data']);
        $this->assign('lists', $lists);
        $this->assign('request', input("request."));
        $this->getAllNotesType(1);//1话题 2梦话
        return view('lists');
    }

    /**
     * 删除
     * 支持批量删除和单条删除
     * @return mixed
     */
    public function delData()
    {
        $return = [];
        $id = trim(input("request.id"));//auth
        if (empty($id)) {
            $return = ['err' => 1, 'msg' => '操作失败'];
            return json($return);
        }
        $res = $this->_model->updateData(array('is_delete' => 1), $id);
        if ($res) {
            $return = ['err' => 0, 'msg' => '操作成功'];
            return json($return);
        } else {
            $return = ['err' => 3, 'msg' => '操作失败'];
            return json($return);
        }

    }


    /**
     * 删除
     * 支持批量删除和单条删除附件
     * @return mixed
     */
    public function delFilesData()
    {
        $return = [];
        $id = trim(input("request.id"));//auth
        if (empty($id)) {
            $return = ['err' => 1, 'msg' => '操作失败'];
            return json($return);
        }
        $model = new \app\admin\model\NotesFiles();
        $res = $model->delData(array("id" => $id));
        if ($res) {
            $return = ['err' => 0, 'msg' => '操作成功'];
            return json($return);
        } else {
            $return = ['err' => 3, 'msg' => '操作失败'];
            return json($return);
        }

    }

    /**
     * 文件排序
     * @return \think\response\Json
     */
    public function fileSorts()
    {
        $return = [];
        $id = trim(input("request.id"));//auth
        $sorts = trim(input("request.sorts"));//auth
        if (empty($id)) {
            $return = ['err' => 1, 'msg' => '操作失败'];
            return json($return);
        }
        if (empty($sorts)) {
            $sorts = 0;
        }
        $model = new \app\admin\model\NotesFiles();
        $res = $model->updateData(array('sorts' => $sorts), $id);
        if ($res || $res == 0) {
            $return = ['err' => 0, 'msg' => '操作成功'];
            return json($return);
        } else {
            $return = ['err' => 3, 'msg' => '操作失败'];
            return json($return);
        }

    }


    public function addData()
    {
        $sys_opt = trim(input("request.sys_opt"));//auth
        if ($sys_opt) {
            $data1 = $_REQUEST['data'];
            $data2 = array(
                'uid' => $this->LoginUserInfo['UserInfo']['id'],
                'ctime' => time(),
                'utime' => time(),
                'ty' => 1
            );
            $data = array_merge($data1, $data2);
            $res = $this->_model->add($data);
            if ($res) {
                $return = ['err' => 0, 'msg' => '操作成功'];
                return json($return);
            } else {
                $return = ['err' => 3, 'msg' => '操作失败'];
                return json($return);
            }
        }
        $title = "添加";
        $this->getAllNotesType(1);//1话题 2梦话
        $this->assign('title', $title);
        return view('addData');
    }

    public function infoData()
    {

        $id = trim(input("request.id"));//auth

        $info = $this->_model->getDataForWhere(array('id' => $id));

        $info['UserInfo'] = array();
        if ($info['uid']) {
            $info['UserInfo'] = getUserInfoForID($info['uid']);
        }
        $FileLists = getNotesFiles($id, 0, "sorts desc,id desc");//获取发帖附件数据
        $this->assign('FileLists', $FileLists);

        $this->getAllNotesType(1);//1话题 2梦话
        $this->assign('info', $info);
        $title = "详情";
        $this->assign('title', $title);
        $this->assign('id', $id);
        return view('infoData');

    }


    /**
     * 回复列表
     * @return \think\response\View
     */
    public function replyList()
    {
        $ser_key = trim(input("request.ser_key"));//auth
        $ser_val = trim(input("request.ser_val"));//auth
        $tid = trim(input("request.tid"));//auth

        if ($ser_key && $ser_val) {
            $where[$ser_key] = array('like', '%' . $ser_val . '%');
        }

        $where['type'] = '0';//
        $where['is_delete'] = '0';
        $where['tid'] = $tid;
        $model = new \app\admin\model\NotesReply();
        $lists = $model->lists($where, $this->pagesize);
        $lists['data'] = changeUidToUserinfoForLists($lists['data'], 'uid', "touid");
        $this->assign('lists', $lists);
        $this->assign('tid', $tid);
        $this->assign('request', input("request."));
        return view('replyList');
    }


    /**
     * 删除
     * 支持批量删除和单条删除
     * @return mixed
     */
    public function delReplyData()
    {
        $return = [];
        $id = trim(input("request.id"));//回复表中的id
        $tid = trim(input("request.tid"));//帖子ID
        if (empty($id)) {
            $return = ['err' => 1, 'msg' => '操作失败'];
            return json($return);
        }
        $model = new \app\admin\model\NotesReply();
        $res = $model->updateData(array('is_delete' => 1), $id);
        if ($res) {
            $return = ['err' => 0, 'msg' => '操作成功'];
            return json($return);
        } else {
            $return = ['err' => 3, 'msg' => '操作失败'];
            return json($return);
        }

    }

    public function replyInfoData()
    {

        $id = trim(input("request.id"));//auth
        $tid = trim(input("request.tid"));//auth

        $model = new \app\admin\model\NotesReply();
        $info = $model->getDataForWhere(array('id' => $id, 'tid' => $tid));

        $info['UserInfo'] = array();
        if ($info['uid']) {
            $info['UserInfo'] = getUserInfoForID($info['uid']);
        }
        $FileLists = getNotesFiles($id, 1, "sorts desc,id desc");//获取发帖附件数据
        $this->assign('FileLists', $FileLists);

        $this->getAllNotesType(1);//1话题 2梦话
        $this->assign('info', $info);
        $title = "详情";
        $this->assign('title', $title);
        $this->assign('id', $id);
        $this->assign('tid', $tid);
        return view('replyInfoData');

    }

    public function editData()
    {

        $id = trim(input("request.id"));//auth
        $sys_opt = trim(input("request.sys_opt"));//auth
        //查询用户
        $info = $this->_model->getDataForWhere(array('id' => $id));

        if ($sys_opt) {
            $data1 = $_REQUEST['data'];
            $w = array(
                'id' => $id
            );
            $data2 = array(
                'utime' => time()
            );
            $data = array_merge($data1, $data2);
            $res = $this->_model->updateDataForWhere($data, $w);

            if ($res || ($res === 0)) {

                $return = ['err' => 0, 'msg' => '操作成功'];
                return json($return);
            } else {
                $return = ['err' => 3, 'msg' => '操作失败'];
                return json($return);
            }
        }


        $this->assign('info', $info);
        //设置全局信息
        $title = "编辑";
        $this->getAllNotesType(1);//1话题 2梦话
        $this->assign('title', $title);
        $this->assign('id', $id);
        return view('editData');

    }

    /**
     * 添加附件
     * @return \think\response\Json|\think\response\View
     */
    public function addFiles()
    {
        $pid = trim(input("request.pid"));//auth
        $sys_opt = trim(input("request.sys_opt"));//auth
        $FileLists = getNotesFiles($pid, 0, "sorts desc,id desc");//获取发帖附件数据
        $this->assign('FileLists', $FileLists);
        //设置全局信息
        $title = "添加附件";
        $this->assign('title', $title);
        $this->assign('pid', $pid);
        return view('addFiles');
    }



    /**
     * 支持大文件分片上传
     */
    public function plAddData()
    {
        header('Content-type: text/plain');
        $scenePic = request()->file('file');
        $path = generaUploadPath($this->LoginUserInfo['UserInfo']['id']);
        $pid = $_REQUEST['pid'];
        //分片上传处理 start
        $totleFileName = $_REQUEST['name'];//文件原始名称
        $chunks = $_REQUEST['chunks'];//如果是分片文件上传 那么 这个大于0，总的分片数量
        $chunk = $_REQUEST['chunk'];//如果是分片文件上传，那么这个大于0，当前分片数量
        if (!empty($chunks)) {
            import("myCal.FileChunksUpload#class", VENDOR_PATH);
            $fileChunksUpload = new \FileChunksUpload();
            $tempUploadFile = $scenePic->getInfo("tmp_name");
            $chunkPath = $fileChunksUpload->getChunkPath();//分时文件临时目录
            $fileChunksUpload->dealChunks($chunkPath, $totleFileName, $chunks, $chunk, $tempUploadFile);
            //分片上传完了 检查是否所有分片都上传了
            $isAllExist = $fileChunksUpload->checkChunks($chunkPath, $totleFileName, $chunks);

            if ($isAllExist == false) {//表示文件分片还没有上传完 等待下一个分片
                exit;
            } else {//表示分片上传完毕，合并文件
                $combineFlag = $fileChunksUpload->combineChunks($chunkPath, $totleFileName, $chunks, $path,1);

                if ($combineFlag['err'] == 0) {
                    $this->addNotesFiles($pid, array($combineFlag['url']), 0);
                    echo('{"jsonrpc" : "2.0", "result" : "success", "id" : "id"}');
                    exit;
                } else {
                    echo('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "上传失败"}, "id" : "id"}');
                    exit;
                }
            }
        }
        //分片上传处理 end


        $resultData = uploadPicture($scenePic, $path);
        $pic = '';


        if ($resultData['err'] == '0') {
            $pic = $resultData['file']['url'];
        }

        $pic = str_replace("\\", "/", $pic);
        $iData = array(
            'url' => $pic,
            'pic' => $pic,
            'thumb' => ""
        );
        if (empty($iData['url'])) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "上传失败"}, "id" : "id"}');
        }
        $res = $this->addNotesFiles($pid, array($iData['url']), 0);
        if ($res) {
            die('{"jsonrpc" : "2.0", "result" : "success1", "id" : "id"}');
        } else {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "上传失败"}, "id" : "id"}');
        }
    }

    private function addNotesFiles($tid, $json_images, $typeid = 0)
    {

        $insertData = array();
        foreach ($json_images as $key => $val) {
            $ty = 1;
            $suffix = getSuffixForFile($val);
            if (in_array($suffix, ['jpg', 'jpeg', 'png'])) {
                $ty = 1;
            } else if (in_array($suffix, ['mp3', 'mp4', 'avi', 'wmv', 'flv'])) {
                $ty = 2;
            } else {
                $ty = 3;
            }
            $tempData = array(
                'tid' => $tid,
                'file' => $val,
                'thumb' => $val,
                'ctime' => time(),
                'ty' => $ty,
                'typeid' => $typeid,
            );
            $insertData[] = $tempData;
        }
        if (empty($insertData)) {
            return false;
        }
        $model = new \app\admin\model\NotesFiles();
        return $model->addAll($insertData);
    }
}